const http = require('http');
const fs = require('fs');
const queryString = require('querystring')

const server = http.createServer((req, res) => {

    if (req.headers['origin'] === 'http://127.0.0.1:8080') {
        res.setHeader('Access-Control-Allow-Origin', '*')
        res.setHeader('Access-Control-Allow-Methods', 'PUT')
    }

    // 静态资源处理
    if (/.html$/.test(req.url)) {
        let filePath = __dirname + '/' + req.url
        res.writeHead(200);
        fs.createReadStream(filePath).pipe(res)
    } else {
        if (req.url === '/login') {
            if (req.method === 'OPTIONS') {
                res.statusCode = 200
                res.end('')
            } else if (req.method === 'PUT') {
                let chunks = []
                req.on('data', data => {
                    chunks.push(data);
                })
                req.on('end', function() {
                    let body = queryString.parse(chunks.toString())
                    console.log(body)
                    let result = {
                        success: true,
                        msg: '',
                        data: {}
                    }
                    res.statusCode = 200
                    res.end(JSON.stringify(result));
                })
            }
        }
    }
})

server.listen(3001, () => {
    console.log('server is runing localhost:3001')
})
